import gulp from "gulp";
import postcss from "gulp-postcss";
import autoprefixer from "autoprefixer";
import cssnano from "cssnano";
import babel from "gulp-babel";
import gulpSass from "gulp-sass";
import sassCompiler from 'sass';
import postcssModules from 'postcss-modules';
import path from 'path';
import fs from 'fs';
import gulpReplace from "gulp-replace";

const sass = gulpSass(sassCompiler);
const cssPrefix = 'sun-ui';
const root = 'testUI'
const componentsRoot = `${root}\\components`


const paths = {
    dest: {
        es: 'es',
        lib: 'lib'
    },
    styles: [
        'components/**/*.scss',
        'components/**/*.css',
    ],
    scripts: [
        'components/**/*.{ts,tsx}',
    ]
}

const compileESM = () => {
    const {scripts, dest} = paths
    return gulp
        .src(scripts)
        .pipe(gulpReplace('.scss', '.js'))
        .pipe(babel())
        .pipe(gulp.dest(dest.es))
}

const getJSONFromCssModules = (cssFileName, json, outFileName) => {
    const {dest} = paths;
    // console.log('getJSONFromCssModules', {cssFileName, outFileName})
    const cssName = path.basename(cssFileName, '.css');
    const jsFileName = cssFileName.replace(componentsRoot, `${root}\\${dest.es}`).replace('.css', '.js');
    const dirPath = path.dirname(jsFileName);
    // console.log('jsFileName', {cssName, jsFileName, dirPath})
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, {recursive: true})
    }
    fs.writeFileSync(jsFileName, `
    import './${cssName}.css'
    export default ${JSON.stringify(json)}`);
}

const getCssScopedName = (name, fileName) => {
    // console.log('getCssScopedName======', {name, fileName})
    const basePath = fileName.replace(/.*\\testUI\\components\\(.*)\\style.*/, '$1')
    // console.log('basePath========', basePath)

    return `${cssPrefix}-${basePath}-${name}`;
}

const compileSCSS = () => {
    const {dest, styles} = paths;
    const postcssPlugins = [
        postcssModules({getJSON: getJSONFromCssModules, generateScopedName: getCssScopedName}),
        autoprefixer({
            overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8', '> 1%'],
            grid: true,
        }),
        cssnano({
            zindex: false,
            reduceIdents: false
        })
    ];
    return gulp
        .src(styles)
        .pipe(sass())
        .pipe(postcss(postcssPlugins))
        .pipe(gulp.dest(dest.es));
}

export const build = gulp.parallel(compileESM, compileSCSS);

export default build;